package org.cy.evolution.net.http.interceptor;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import org.cy.evolution.framework.app.EvolutionApplication;
import org.cy.evolution.utils.NetworkUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.CacheControl;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HttpCommonInterceptor implements Interceptor {

    private static final String TAG = "HttpCommonInterceptor";

    private Map<String, String> headerParamMap = new HashMap<>(0);
    private List<String> headerParamLines = new ArrayList<>(0);

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Log.d(TAG, "add common params to header");
        Request oldRequest = chain.request();
        Headers.Builder headersBuilder = oldRequest.headers().newBuilder();
        Request.Builder requestBuilder = oldRequest.newBuilder();

        if (!headerParamLines.isEmpty()) {
            for(String line : headerParamLines) {
                headersBuilder.add(line);
            }
            requestBuilder.headers(headersBuilder.build());
        }

        if (!headerParamMap.isEmpty()) {
            for(Map.Entry<String, String> header: headerParamMap.entrySet()) {
                requestBuilder.header(header.getKey(), header.getValue());
            }
        }

        // 开始配置缓存
        boolean isNetAvailable = NetworkUtil.isConnected(EvolutionApplication.getContext());
        if(isNetAvailable) {
            requestBuilder.cacheControl(CacheControl.FORCE_NETWORK);
        } else {
            requestBuilder.cacheControl(CacheControl.FORCE_CACHE);
        }
        Request newRequest = requestBuilder.build();

        Response newResponse = chain.proceed(newRequest);
        if (isNetAvailable) {
            newResponse = newResponse.newBuilder()
                    .removeHeader("Pragma")
                    // 有网络时 设置缓存超时时间1个小时
                    .header("Cache-Control", "public, max-age=" + 60 * 60)
                    .build();
        } else {
            newResponse = newResponse.newBuilder()
                    .removeHeader("Pragma")
                    // 无网络时，设置超时为1周
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + 7 * 24 * 60 * 60)
                    .build();
        }
        return newResponse;
    }

    public static class Builder {

        private HttpCommonInterceptor httpCommonInterceptor;

        public Builder() {
            this.httpCommonInterceptor = new HttpCommonInterceptor();
        }

        public Builder addHeaderParams(@Nullable String key, @Nullable String value) {
            httpCommonInterceptor.headerParamMap.put(key, value);
            return this;
        }

        public Builder addHeaderParams(@Nullable String key, @Nullable Integer value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(@Nullable String key, @Nullable Long value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(@Nullable String key, @Nullable Float value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(@Nullable String key, @Nullable Double value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderLine(@Nullable String header) {
            httpCommonInterceptor.headerParamLines.add(header);
            return this;
        }

        public HttpCommonInterceptor build() {
            return httpCommonInterceptor;
        }
    }
}
